package services

import (
	"encoding/json"
	"rustdesk_api_server/api/request"
	"rustdesk_api_server/models"
	"rustdesk_api_server/repository"
	"strings"
)

var AddressBook = new(AddressBookService)

type AddressBookService struct{}

func (ab *AddressBookService) DeleteAll(user models.User) error {
	err := repository.Peers.DeleteAll(user)
	if err != nil {
		return err
	}
	return repository.Tags.DeleteAll(user)
}

func (ab *AddressBookService) UpdateTags(user_id uint, data request.AddressBookUpdateFormData) bool {
	if len(data.Tags) == 0 {
		return false
	}
	tags := []models.Tags{}
	for _, t := range data.Tags {
		tags = append(tags, models.Tags{
			UserId: user_id,
			Tag:    t,
		})
	}

	err := repository.Tags.Updates(tags)
	if err != nil {
		return false
	}

	return true
}

func (ab *AddressBookService) UpdatePeers(user_id uint, data request.AddressBookUpdateFormData) bool {
	if len(data.Peers) == 0 {
		return false
	}

	peers := []models.Peer{}

	for _, p := range data.Peers {
		if len(p.Id) > 16 || p.Username == "----" {
			continue
		}
		peers = append(peers, models.Peer{
			UserId:   user_id,
			Id:       string(p.Id),
			Hostname: p.Hostname,
			Username: p.Username,
			Alias:    p.Alias,
			Platform: p.Platform,
			Tags:     strings.Join(p.Tags, ","),
		})
	}
	if len(peers) == 0 {
		return true
	}

	err := repository.Peers.Updates(peers)
	if err != nil {
		return false
	}

	return true
}

func (ab *AddressBookService) ExportAll(user_id uint) string {
	tags := repository.Tags.GetByUserId(user_id)

	peers := repository.Peers.GetByUserId(user_id)

	var req request.AddressBookUpdateFormData
	req.Tags = []string{}

	for _, v := range tags {
		req.Tags = append(req.Tags, v.Tag)
	}

	req.Peers = []request.Peer{}
	for _, v := range peers {
		req.Peers = append(req.Peers, request.Peer{
			Id:       v.Id,
			Username: v.Username,
			Hostname: v.Hostname,
			Alias:    v.Alias,
			Platform: v.Platform,
			Tags:     strings.Split(v.Tags, ","),
		})
	}

	ret, _ := json.Marshal(req)

	return string(ret)
}
